<?php
use lib\Log;
use lib\Cache;

#捕获Warring错误
set_error_handler('displayErrorHandler');
function displayErrorHandler($errno, $errstr, $filename, $line)
{
    $error_no_arr = [
        1    => 'ERROR',
        2    => 'WARNING',
        4    => 'PARSE',
        8    => 'NOTICE',
        16   => 'CORE_ERROR',
        32   => 'CORE_WARNING',
        64   => 'COMPILE_ERROR',
        128  => 'COMPILE_WARNING',
        256  => 'USER_ERROR',
        512  => 'USER_WARNING',
        1024 => 'USER_NOTICE',
        2047 => 'ALL',
        2048 => 'STRICT'
    ];

    if (in_array($errno, [1, 2, 4])) {
        Log::out('sysError', 'I', "File:{$filename} on Line:{$line} \n" . $error_no_arr[$errno] . ":" . $errstr . "\n");
        #throw new \Exception($error_no_arr[$errno] . ":". $errstr, $errno);
    }
}

/**
 * 输出变量的内容，通常用于调试
 *
 * @param mixed $vars 要输出的变量
 * @param string $label
 * @param boolean $return
 * @package Core
 *
 */
function dump($vars, $label = '', $return = false)
{
    if (ini_get('html_errors')) {
        $content = "<pre>\n";
        if ($label != '') {
            $content .= "<strong>{$label} :</strong>\n";
        }
        $content .= htmlspecialchars(print_r($vars, true));
        $content .= "\n</pre>\n";
    } else {
        $content = $label . " :\n" . print_r($vars, true);
    }
    if ($return) {
        return $content;
    }
    echo $content;
    return null;
}

function json($vars = [], $format = 'json', $callback = 'callback')
{
    if ($format == 'json') {
        header("Content-type: application/json;charset=utf-8");
        $data = updateNull($vars);
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
    } else {
        header("Content-type: text/javascript;charset=utf-8");
        $data = updateNull($vars);
        echo "{$callback}(" . json_encode($data, JSON_UNESCAPED_UNICODE) . ")";
    }
}

function jsonp($data, int $code = 200)
{
    http_response_code($code);
    if ($code != 200) {
        $data = ['msg' => $data];
    }
    json($data);
}

function ret($ret = 0, $msg = 'ok', $data=null)
{
    $ret = [
        'ret' => $ret,
        'msg' => $msg,
    ];
    if (!empty($data)) {
        $ret['data'] = $data;
    }
    json($ret);
    exit;
}

function updateNull(&$onearr)
{
    if (!empty($onearr) && is_array($onearr)) {
        foreach ($onearr as $k => $v) {
            if (is_array($v)) {
                $onearr[$k] = updateNull($v);
            } else {
                if ($v === NULL) {
                    $onearr[$k] = '';
                }
            }
        }
    }
    return $onearr;
}

/***保存SQL记录到redis***/
function remember($key, $ttl, callable $func)
{
    $cache_enable = Yaf_Registry::get('config')->cache->redis->enable;
    if ($cache_enable && Cache::exists($key)) {
        return Cache::get($key);
    }
    $rows = call_user_func($func);
    if ($cache_enable) {
        Cache::set($key, $rows, $ttl);
    }
    return $rows;
}

/***遗忘***/
function forget($key)
{
    $cache_enable = Yaf_Registry::get('config')->cache->redis->enable;
    if ($cache_enable && Cache::exists($key)) {
        Cache::delete($key);
    }
}

#获取请求头
function getHeader($key=''){
    if($key=='') {
        $headers = [];
        foreach ($_SERVER as $name => $value) {
            if (substr($name, 0, 5) == 'HTTP_') {
                $headers[strtolower(substr($name, 5))] = $value;
            }
        }
        return $headers;
    }else{
        foreach ($_SERVER as $name => $value) {
            if (substr($name, 0, 5) == 'HTTP_' && strtolower($key)==strtolower(substr($name, 5))) {
                return $value;
            }
        }
    }
}

/***PHP上传文件到七牛cdn***/
function uploadToCDN($filePath, $cdnfileName)
{
    // 需要填写你的 Access Key 和 Secret Key
    $accessKey = Yaf_Registry::get('config')->application->cdn->accessKey;
    $secretKey = Yaf_Registry::get('config')->application->cdn->secretKey;

    // 构建鉴权对象
    $auth = new \Qiniu\Auth($accessKey, $secretKey);
    // 要上传的空间
    $bucket = Yaf_Registry::get('config')->application->cdn->bucket;

    // 生成上传 Token
    $token = $auth->uploadToken($bucket);

    // 上传到七牛后保存的文件名
    $key = $cdnfileName;

    // 初始化 UploadManager 对象并进行文件的上传
    $uploadMgr = new \Qiniu\Storage\UploadManager;

    // 调用 UploadManager 的 putFile 方法进行文件的上传
    [$ret, $err] = $uploadMgr->putFile($token, $key, $filePath);
    if ($err !== null) {
        return false;
    } else {
        return Yaf_Registry::get('config')->application->cdn->url . $ret['key'];
    }
}

function getIp()
{
    if (@$_SERVER["
    "])
        $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
    else if (@$_SERVER["HTTP_CLIENT_IP"])
        $ip = $_SERVER["HTTP_CLIENT_IP"];
    else if (@$_SERVER["REMOTE_ADDR"])
        $ip = $_SERVER["REMOTE_ADDR"];
    else if (@getenv("HTTP_X_FORWARDED_FOR"))
        $ip = getenv("HTTP_X_FORWARDED_FOR");
    else if (@getenv("HTTP_CLIENT_IP"))
        $ip = getenv("HTTP_CLIENT_IP");
    else if (@getenv("REMOTE_ADDR"))
        $ip = getenv("REMOTE_ADDR");
    else
        $ip = "Unknown";
    return $ip;
}

/**
 * PHP生成随机字符串
 * @param int $length
 * @param int $type [0:全类型 1:数字 2:小写字母 3:大写字母]
 * @return string
 */
function randStr($length = 10, $type = 0): string
{
    switch ($type) {
        case 1:
            $characters = '1234567890';
            break;
        case 2:
            $characters = 'abcdefghijkmnopqrstuvwxyz';
            break;
        case 3:
            $characters = 'ABCDEFGHIJKLMNPOQRSTUVWXYZ';
            break;
        default:
            $characters = '23456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ';
            break;
    }
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}

/**
 * 跳转
 *
 * @param      $url
 * @param null $headers
 */
function redirect($url)
{
    echo "<script>top.location.href='{$url}';</script>";
    exit;
    /* if (!empty($url))
    {
        if ($headers)
        {
            if (!is_array($headers))
                $headers = array($headers);

            foreach ($headers as $header)
                header($header);
        }

        header('Location: ' . $url);
        exit;
    } */
}

function pick(string $url, $postData = '')
{
    $row  = parse_url($url);
    $host = $row['host'];
    $port = isset($row['port']) ? $row['port'] : 80;
    $file = $row['path'];
    if (is_array($postData)) {
        $postData = http_build_query($postData);
    }
    $len = strlen($postData);
    $fp  = @fsockopen($host, $port, $errno, $errstr, 10);
    if (!$fp) {
        return "$errstr ($errno)\n";
    } else {
        $receive = '';
        $out     = "POST $file HTTP/1.1\r\n";
        $out     .= "Host: $host\r\n";
        $out     .= "Content-type: application/x-www-form-urlencoded\r\n";
        $out     .= "Connection: Close\r\n";
        $out     .= "Content-Length: $len\r\n\r\n";
        $out     .= $postData;
        fwrite($fp, $out);
        while (!feof($fp)) {
            $receive .= fgets($fp, 128);
        }
        fclose($fp);
        $receive = explode("\r\n\r\n", $receive);
        unset($receive[0]);
        return implode("", $receive);
    }
}

/**
 *curl采集函数
 * @param string $url
 * @param string $postData
 * @param array $header
 * @param string $referer
 * @param bool $proxyip
 * @param string $compression
 * @return bool|string
 */
function curl_request(string $url, $postData = '', $header = [], $referer = 'http://www.baidu.com', $proxyip = false, $compression = 'gzip, deflate')
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    if (!empty($header)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    }
    if (!empty($postData)) {
        curl_setopt($ch, CURLOPT_POST, 1);
        if (is_array($postData)) {
            $postData = http_build_query($postData);
        }
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    }
    if (!empty($proxyip)) {
        curl_setopt($ch, CURLOPT_PROXY, $proxyip);
    }
    if (!empty($compression)) {
        curl_setopt($ch, CURLOPT_ENCODING, $compression);
    }
    curl_setopt($ch, CURLOPT_REFERER, $referer ?? "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11');
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

function curl_json($url, $jsonStr)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($jsonStr)
        ]
    );
    $response = curl_exec($ch);
    #$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    return $response;
}

/**
 * 数组 转 对象
 *
 * @param array $arr 数组
 * @return object
 */
function array_to_object($arr) {
    if (gettype($arr) != 'array') {
        return;
    }
    foreach ($arr as $k => $v) {
        if (gettype($v) == 'array' || getType($v) == 'object') {
            $arr[$k] = (object)array_to_object($v);
        }
    }
    return (object)$arr;
}

/**
 * 对象 转 数组
 *
 * @param object $obj 对象
 * @return array
 */
function object_to_array($obj) {
    $obj = (array)$obj;
    foreach ($obj as $k => $v) {
        if (gettype($v) == 'resource') {
            return;
        }
        if (gettype($v) == 'object' || gettype($v) == 'array') {
            $obj[$k] = (array)object_to_array($v);
        }
    }
    return $obj;
}
